//
//  ELAppService.swift
//  WZApp
//
//  Created by evol on 2018/7/2.
//  Copyright © 2018年 evol. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import Moya
import HandyJSON

class ELAppService {
    // 获取所有页签
    static func loadLabels() -> Observable<[ELTagModel]> {
        return provider.rx.request(.labels).mapModelList(ELTagModel.self).asObservable()
    }
    // 获取业态信息
    static func loadAnnotationInfomation(_ id: NSInteger) -> Observable<ELAnnotationInfomation> {
        return provider.rx.request(.annotationInfomation(id: id)).mapModel(ELAnnotationInfomation.self).asObservable()
    }
    // 获取定位信息
    static func loadLocationDatas(_ version: NSInteger) -> Observable<[ELLocationModel]> {
        return provider.rx.request(.locationDatas(version: version)).flatMap {response -> Single<[ELLocationModel]> in
            let jsonString = String(data: response.data, encoding: .utf8)
            let apiModel = JSONDeserializer<APIModel>.deserializeFrom(json: jsonString)!
            if let data = apiModel.data as? Dictionary<String, Any> {
                let version = data["data_version"]
                UserDefaults.standard.set(version, forKey: USERDEFAULT_LOCATION_VERSION)
                let locations = data["pic_gis"] as? Array<Dictionary<String, Any>>
                let models = locations?.compactMap({ ELLocationModel.deserialize(from: $0 ) })
                return Single.just(models ?? [])
                
            }
            return Single.just([ELLocationModel()])
        }.asObservable()
    }
    
    // 获取路线
    static func loadRouteLines(startId: NSInteger, endId: NSInteger) -> Observable<[ELLineModel]> {
        return provider.rx.request(.routeLines(startId: startId, endId: endId)).mapModelList(ELLineModel.self).asObservable()
    }
    
    // 获取最近的路线点
    static func loadNearestRoutePoint(_ point: CGPoint) -> Observable<NSInteger> {
        return provider.rx.request(.nearestRoutePoint(point: point)).flatMap{ (response) -> Single<NSInteger> in
            let jsonString = String(data: response.data, encoding: .utf8)
            let apiModel = JSONDeserializer<APIModel>.deserializeFrom(json: jsonString)!
            if let data = apiModel.data as? Dictionary<String, Any> {
                if let routeId = data["id"] as? NSInteger {
                    return Single.just(routeId)
                }
            }
            return Single.just(0)
        }.asObservable()
    }
}
